package com.hjj.springboot.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hjj.springboot.entity.HealthPlan;
import com.hjj.springboot.entity.PlanDetail;
import com.hjj.springboot.entity.R;
import com.hjj.springboot.entity.UserHealthInfo;
import com.hjj.springboot.service.IHealthPlanService;
import com.hjj.springboot.service.IPlanDetailService;
import com.hjj.springboot.service.IUserHealthInfoService;
import com.hjj.springboot.util.CalorieCalculator;
import com.hjj.springboot.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/my/healthPlan")
public class HealthPlanController {

    @Autowired
    private IHealthPlanService healthPlanService;

    @Autowired
    private IUserHealthInfoService userHealthInfoService;

    @Autowired
    private IPlanDetailService planDetailService;


    @GetMapping("/findAll")
    public R findAll(String uid){
        List<HealthPlan> healthPlanList=healthPlanService.list(new QueryWrapper<HealthPlan>().eq("uid",uid).orderByDesc("isOngoing"));
        Map<String,Object> map = new HashMap<>();
        map.put("message",healthPlanList);
        return R.ok(map);
    }

    @PostMapping("/add")
    public R add(@RequestBody HealthPlan healthPlan){
        System.out.println(healthPlan);
        UserHealthInfo user = userHealthInfoService.getOne(new QueryWrapper<UserHealthInfo>().eq("uid",healthPlan.getUid()));
        int dailyCalories = CalorieCalculator.calculatePlanCalories(user,healthPlan);
        System.out.println(dailyCalories);
        healthPlan.setDailyCalories(dailyCalories);
        healthPlanService.save(healthPlan);
        return R.ok();
    }

    @GetMapping("/delete")
    public R delete(Integer id){
        healthPlanService.removeById(id);
        planDetailService.remove(new QueryWrapper<PlanDetail>().eq("mid",id));
        return R.ok();
    }

    @GetMapping("/todayProgress")
    public R todayProgress(String uid){
        HealthPlan healthPlan = healthPlanService.getOne(new QueryWrapper<HealthPlan>().eq("uid",uid).eq("isOngoing",1));
        double todayCalories = planDetailService.list(new QueryWrapper<PlanDetail>()
                                                .eq("mid", healthPlan.getId())
                                                .apply("DATE(time) = DATE({0})", LocalDate.now()))  // 使用数据库函数处理日期比较
                                                .stream().mapToDouble(PlanDetail::getCalories).sum();
        double percent = Math.round((todayCalories/healthPlan.getDailyCalories())*100);
        HashMap<String,Object> map = new HashMap<>();
        map.put("dailyCalories",healthPlan.getDailyCalories());
        map.put("percent",percent);
        return R.ok(map);
    }

    @GetMapping("/lineCharts")
    public R lineCharts(String uid){
        HealthPlan healthPlan = healthPlanService.getOne(new QueryWrapper<HealthPlan>().eq("uid",uid).eq("isOngoing",1));
        List<PlanDetail> planDetailList = planDetailService.list(new QueryWrapper<PlanDetail>().eq("mid",healthPlan.getId()));

        // 创建ZoneId对象以重用
        ZoneId zoneId = ZoneId.systemDefault();

        // 使用Map来同时存储每日的建议摄入量与实际摄入量
        Map<LocalDate, Double> dateToIntakeDataMap = new TreeMap<>();
        Map<LocalDate, Integer> dateToSuggestionDataMap = new TreeMap<>();

        planDetailList.forEach(planDetail -> {
            LocalDate date = planDetail.getTime().toInstant().atZone(zoneId).toLocalDate();
            dateToIntakeDataMap.merge(date, planDetail.getCalories(), Double::sum);
            dateToSuggestionDataMap.put(date, healthPlan.getDailyCalories());
        });

        List<LocalDate> dates = new ArrayList<>(dateToIntakeDataMap.keySet());
        List<Double> intakes = dates.stream().map(dateToIntakeDataMap::get).collect(Collectors.toList());
        List<Integer> suggestions = dates.stream().map(dateToSuggestionDataMap::get).collect(Collectors.toList());
        HashMap<String,Object> map = new HashMap<>();
        map.put("dates",dates);
        map.put("intakes",intakes);
        map.put("suggestions",suggestions);
        return R.ok(map);
    }

    @GetMapping("/getDetail")
    public R getDetail(Integer id){
        List<PlanDetail> planDetailList = planDetailService.list(new QueryWrapper<PlanDetail>().eq("mid",id));
        HashMap<String,Object> map = new HashMap<>();
        map.put("detail",planDetailList);
        return R.ok(map);
    }

    @PostMapping("/addDetail")
    public R addDetail(@RequestBody PlanDetail planDetail, @RequestHeader(value="token") String token){
        Claims claims = JwtUtils.validateJWT(token).getClaims();
        if(claims!=null){
            Integer mid = healthPlanService.getOne(new QueryWrapper<HealthPlan>().eq("uid",claims.getId()).eq("isOngoing",1)).getId();
            planDetail.setMid(mid);
            planDetail.setTime(new Date());
            System.out.println(planDetail);
            planDetailService.save(planDetail);
            return R.ok();
        }
        return R.error();
    }
}
